<template>
    <div class="crm-enterprise-container">
        <el-card shadow="hover" class="mb10" v-auth="'crm:enterprise:list'">
            <el-form :inline="true" :model="search">
                <el-form-item>
                    <el-input v-model="search.enterpriseName" placeholder="请输入企业名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.legalName" placeholder="请输入法定代表人" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.mobile" placeholder="请输入手机号码" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-input v-model="search.userName" placeholder="请输入所属用户名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-input v-model="search.deptName" placeholder="请输入所属部门名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
					<el-cascader
						placeholder="请选择所属部门"
						v-model="search.deptId"
						:options="depts"
						:props="{expandTrigger: 'hover', emitPath: false, checkStrictly: true, value: 'id', label: 'deptName', children: 'children' }"
						class="w100"
						filterable
						clearable>
					</el-cascader>
				</el-form-item>
                <el-form-item v-if="search.more">
                    <el-date-picker type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
                        unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-search" type="primary" @click="onTableSearch()">查询</el-button>
                    <el-button icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
                    <el-button v-if="!search.more" @click="onMoreSearch(true)" type="primary" link>更多</el-button>
                    <el-button v-if="search.more" @click="onMoreSearch(false)" type="info" link>收起</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="hover">
            <el-button v-auth="'crm:enterprise:add'" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddCrmEnterprise()">新增</el-button>
            <el-button v-auth="'crm:enterprise:edit'" type="primary" class="ml10" icon="el-icon-edit" @click="onOpenEditCrmEnterprise()" :disabled="tableData.selections.length != 1">修改</el-button>
            <el-button v-auth="'crm:enterprise:remove'" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button>
            <el-table ref="tableCrmEnterpriseRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="center" width="50" show-overflow-tooltip>
                    <template #header>
                        <!-- 使用 el-popover 包裹 el-checkbox-group -->
                        <el-popover placement="bottom-start" :width="100" trigger="click">
                            <template #reference>
                                <!-- 点击触发器：这里放置图标 -->
                                <svg-icon name="el-icon-setting" style="cursor: pointer;"></svg-icon>
                            </template>
                            <!-- el-checkbox-group 放置在此处 -->
                            <el-checkbox-group v-model="tableData.header.selections">
                                <el-checkbox v-for="item in tableData.header.data" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
                            </el-checkbox-group>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column label="企业名称" prop="enterpriseName" v-if="tableData.header.selections.includes('enterpriseName')" min-width="300" show-overflow-tooltip></el-table-column>
                <el-table-column label="社会信用代码" prop="creditCode" v-if="tableData.header.selections.includes('creditCode')" width="300" show-overflow-tooltip></el-table-column>
                <el-table-column label="法定代表人" prop="legalName" v-if="tableData.header.selections.includes('legalName')" width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="手机号码" prop="mobile" v-if="tableData.header.selections.includes('mobile')" width="150" show-overflow-tooltip></el-table-column>
                <!-- <el-table-column label="电话号码" prop="telephone" show-overflow-tooltip></el-table-column> -->
                <!-- <el-table-column label="邮箱号码" prop="email" show-overflow-tooltip></el-table-column> -->
                <!-- <el-table-column label="注册资本" prop="registeredCapital" show-overflow-tooltip></el-table-column> -->
                <el-table-column label="成立日期" prop="enterpriseDate" v-if="tableData.header.selections.includes('enterpriseDate')" width="120" show-overflow-tooltip></el-table-column>
                <el-table-column label="国标行业" prop="industry" v-if="tableData.header.selections.includes('industry')" width="120" show-overflow-tooltip></el-table-column>
                <!-- <el-table-column label="企业规模" prop="enterpriseScale" show-overflow-tooltip></el-table-column> -->
                <!-- <el-table-column label="员工人数" prop="employeeCount" show-overflow-tooltip></el-table-column> -->
                <!-- <el-table-column label="企业简介" prop="description" show-overflow-tooltip></el-table-column> -->
                <!-- <el-table-column label="状态" prop="status" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.status == '0'" class="color-primary">正常</span>
                        <span v-else-if="scope.row.status == '1'" class="color-info">停用</span>
                        <span v-else class="color-danger">删除</span>
                    </template>
                </el-table-column> -->
                <el-table-column label="所属用户" prop="userName" v-if="tableData.header.selections.includes('userName')" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="所属部门" prop="deptName" v-if="tableData.header.selections.includes('deptName')" width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="createTime" v-if="tableData.header.selections.includes('createTime')" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" fixed="right" show-overflow-tooltip min-width="200" v-auths="['crm:enterprise:info', 'crm:enterprise:edit', 'crm:enterprise:remove', 'crm:enterprise:change']">
                    <template #default="scope">
                        <el-button v-auth="'crm:enterprise:info'" type="primary" link @click="onOpenInfoCrmEnterprise(scope.row)">详情</el-button>
                        <el-button v-auth="'crm:enterprise:edit'" type="primary" link @click="onOpenEditCrmEnterprise(scope.row)">修改</el-button>
                        <el-button v-auth="'crm:enterprise:remove'" type="primary" link @click="onTabelRowDel(scope.row)">删除</el-button>
                        <el-button v-auth="'crm:enterprise:change'" type="primary" link @click="onOpenChangeCrmEnterprise(scope.row)">变更</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.total"
            >
            </el-pagination>
        </el-card>
        <AddCrmEnterprise ref="addCrmEnterpriseRef" @submit="onTableSearch"/>
        <EditCrmEnterprise ref="editCrmEnterpriseRef" @submit="onTableSearch"/>
        <ChangeCrmEnterprise ref="changeCrmEnterpriseRef" @submit="onTableSearch"/>
        <InfoCrmEnterprise ref="infoCrmEnterpriseRef"/>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, watch, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Local } from '/@/utils/storage';
import AddCrmEnterprise from '/@/views/crm/enterprise/addCrmEnterprise.vue';
import EditCrmEnterprise from '/@/views/crm/enterprise/editCrmEnterprise.vue';
import ChangeCrmEnterprise from '/@/views/crm/enterprise/changeCrmEnterprise.vue';
import InfoCrmEnterprise from '/@/views/crm/enterprise/infoCrmEnterprise.vue';
import { getCrmEnterpriseList, delCrmEnterprise } from '/@/api/crm/enterprise/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
import { getCrmDeptList } from '/@/api/crm/dept/index';
import { lineToTreeData } from '/@/utils/commonFunction';
export default {
    name: 'crm/enterprise',
    components: { AddCrmEnterprise, EditCrmEnterprise, ChangeCrmEnterprise, InfoCrmEnterprise },
    setup() {
        const tableCrmEnterpriseRef = ref();
        const addCrmEnterpriseRef = ref();
        const editCrmEnterpriseRef = ref();
        const changeCrmEnterpriseRef = ref();
        const infoCrmEnterpriseRef = ref();
        const state = reactive({
            depts: [],
            search:{
                enterpriseName: undefined,
                legalName: undefined,
                mobile: undefined,
                userName: undefined,
                deptName: undefined,
                deptId: undefined,
                startTime: '',
                endTime: '',
                orderBy: 'createTime',
				isAsc: 'desc',
                pageNum: 1,
                pageSize: 10,
                more: false,
            },
            dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false,
                header:{
                    selections: ['enterpriseName', 'legalName', 'mobile', 'userName', 'deptName', 'createTime'],
                    data: [
                        {label: '企业名称', value: 'enterpriseName'},
                        {label: '法定代表人', value: 'legalName'},
                        {label: '手机号码', value: 'mobile'},
                        {label: '所属用户', value: 'userName'},
                        {label: '所属部门', value: 'deptName'},
                        {label: '创建时间', value: 'createTime'},
                    ],
                }
            }
        });

        const loadTableData = (params) => {
            getCrmEnterpriseList(Object.assign(state.search, params)).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableCrmEnterpriseRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        //重置
        const onResetSearch = () => {
            state.dateData.value = [];
            state.search.enterpriseName = undefined;
            state.search.legalName = undefined;
            state.search.mobile = undefined;
            state.search.userName = undefined;
            state.search.deptName = undefined;
            state.search.deptId = undefined;
            state.search.startTime = undefined;
            state.search.endTime = undefined;
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        const onMoreSearch = (more: boolean) => {
            state.search.more = more;
        };
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };
        // 打开新增弹窗
        const onOpenAddCrmEnterprise = (row: object) => {
            addCrmEnterpriseRef.value.openDialog(row);
        };
        // 打开编辑弹窗
        const onOpenEditCrmEnterprise = (row: object) => {
            row = row || state.tableData.selections[0];
            editCrmEnterpriseRef.value.openDialog(row);
        };
        // 打开变更弹窗
        const onOpenChangeCrmEnterprise = (row: object) => {
            row = row || state.tableData.selections[0];
            changeCrmEnterpriseRef.value.openDialog(row);
        };
        // 删除选中行
        const onTabelRowsDel = () => {
            const ids = state.tableData.selections.map(item => item.id);
            if(ids && ids.length > 0){
                ElMessageBox.confirm('确定删除选中的企业信息吗？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    delCrmEnterprise(ids).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('删除成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }
        };
        // 删除当前行
        const onTabelRowDel = (row: object) => {
            ElMessageBox.confirm('确定删除该条企业信息吗？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                delCrmEnterprise([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('删除成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };

        const onOpenInfoCrmEnterprise = (row: object) => {
            row = row || state.tableData.selections[0];
            infoCrmEnterpriseRef.value.openDialog(row);
        };

        // 页面加载时
        onMounted(() => {
            const selections = Local.get('crm_enterprise_header_selections');
            if(selections){
                state.tableData.header.selections = selections;
            }
            loadTableData({});
            getCrmDeptList().then((res: any) => {
                if(res.code == 0 && res.data?.length > 0){
                    state.depts = lineToTreeData(res.data);
                }
            });
        });

        watch(() => state.tableData.header.selections, (selections) => {
            nextTick(() => {
                Local.set('crm_enterprise_header_selections', selections);
                tableCrmEnterpriseRef.value.doLayout();
            });
        }, { deep: true });

        return {
            tableCrmEnterpriseRef,
            addCrmEnterpriseRef,
            editCrmEnterpriseRef,
            changeCrmEnterpriseRef,
            infoCrmEnterpriseRef,
            onTableSearch,
            onResetSearch,
            onMoreSearch,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
            onOpenAddCrmEnterprise,
            onOpenEditCrmEnterprise,
            onTabelRowsDel,
            onTabelRowDel,
            onOpenInfoCrmEnterprise,
            onOpenChangeCrmEnterprise,
            ...toRefs(state),
        };
    },
};
</script>